package ws

import (
	"fmt"
	"svr/src/logs"
	"sync"
	"time"
)

type UpdateTask struct {
	Timestamp time.Time
	Dur       time.Duration
	Func      func(time.Time)
}

var MapUpdates map[string]*UpdateTask

var lockUpdate sync.RWMutex

func AddUpdateTask(name string, dur time.Duration, fn func(time.Time)) {
	lockUpdate.Lock()
	defer lockUpdate.Unlock()
	if MapUpdates == nil {
		MapUpdates = make(map[string]*UpdateTask)
	}
	ut := &UpdateTask{
		Timestamp: time.Now(),
		Dur:       dur,
		Func:      fn,
	}
	if _, ok := MapUpdates[name]; !ok {
		MapUpdates[name] = ut
	} else {
		logs.Errorf("AddUpdateTask error:%s", name)
	}
}

func DelUpdateTask(name string) {
	lockUpdate.Lock()
	defer lockUpdate.Unlock()
	if MapUpdates != nil {
		delete(MapUpdates, name)
	}
}

func updateAll() {
	for {
		if MapUpdates != nil {
			lockUpdate.Lock()
			now := time.Now()
			for k, ut := range MapUpdates {
				if now.After(ut.Timestamp) {
					ut.Timestamp = now.Add(ut.Dur)
					ut.Func(now)
					fmt.Println("update... ", k)
				}
			}
			lockUpdate.Unlock()
		}
		time.Sleep(time.Second)
	}
}

const DurHeartTimeout time.Duration = 60 * time.Second
const DurHeartWait time.Duration = 10 * time.Second

func AddHeartUpdate() {
	AddUpdateTask("heart", DurHeartTimeout, func(now time.Time) {
		if mapTypeToDevs != nil {
			mapTypeToDevs.Walk(func(k interface{}, v interface{}) {
				// typ := k.(msg.DeviceType)
				grp := v.(*DeviceGroup)
				grp.CheckTimeOut(now, unlinkDevice)
			})
		}
	})
}

func unlinkDevice(di *DeviceInfo) {
	di.Close()
}

/*
import (
	"fmt"
	"strconv"
	"strings"
	"svr/src/msg"
	"svr/src/common/conf"
	"svr/src/logs"
	"svr/src/xutil"
)

// 这里主要是维护每个服务器的监听端口的一个状态，包括分配监听端口
// -----------------------------------------------------------------------------------------------------
var mapTypeToAddrListener *xutil.Map //监听地址表[string,]
type ServerGroup struct {            //维护的都是监听服务器的端口
	Type    msg.DeviceType
	Servers []*msg.ServerInfo
}

func createServerGroup(si *msg.ServerInfo) *ServerGroup {
	return &ServerGroup{
		Type:    si.Type,
		Servers: []*msg.ServerInfo{si},
	}
}
func (sg *ServerGroup) AddServer(si *msg.ServerInfo) error {
	if si.Type != sg.Type {
		err := fmt.Errorf("ServerGroup.AddServer Error, Type:%v, add:%+v", sg.Type, si)
		logs.Errorf(err.Error())
		return err
	}
	for _, info := range sg.Servers {
		if info.AddrListen == si.AddrListen {
			err := fmt.Errorf("ServerGroup.AddServer Error, server is have:%+v", si)
			return err
		}
	}
	sg.Servers = append(sg.Servers, si)
	return nil
}

func (sg *ServerGroup) DelServer(si *msg.ServerInfo) (int, bool) {
	if si.Type != sg.Type {
		logs.Errorf("ServerGroup.AddServer Error, Type:%v, add:%+v", sg.Type, si)
		return 0, false
	}
	isFind := false
	for i, info := range sg.Servers {
		if si.AddrListen == info.AddrListen {
			sg.Servers = append(sg.Servers[:i], sg.Servers[i+1:]...)
			isFind = true
			break
		}
	}
	return len(sg.Servers), isFind
}

func AddAddrToMapListener(si *msg.ServerInfo) error {
	if !conf.IsTopServer() {
		return nil
	}
	if mapTypeToAddrListener == nil {
		mapTypeToAddrListener = xutil.CreateMap()
	}
	v := mapTypeToAddrListener.Get(si.Type)
	if v != nil {
		sg := v.(*ServerGroup)
		return sg.AddServer(si)
	} else {
		sg := createServerGroup(si)
		mapTypeToAddrListener.Set(si.Type, sg)
	}
	return nil
}

func DelAddrToMapListener(si *msg.ServerInfo) bool {
	typ := si.Type
	if typ == msg.DeviceType_Unknown {
		return false
	}
	if mapTypeToAddrListener == nil {
		return false
	}
	v := mapTypeToAddrListener.Get(typ)
	if v != nil {
		grp := v.(*ServerGroup)
		ct, isFind := grp.DelServer(si)
		if isFind && ct == 0 {
			mapTypeToAddrListener.Delete(typ)
			logs.Debugf("listen svr type:%d is null", typ)
		}
		return isFind
	}
	return false
}
*/
// -----------------------------------------------------------------------------------------------------

// func checkWebsocketPort(urlStr string) bool {
// 	// WebSocket的URL应该类似于 ws://localhost:8080/path
// 	// 或者 wss://example.com/path 对于加密连接
// 	u := websocket.URL(urlStr)

// 	// 创建WebSocket连接配置
// 	dialer := websocket.Dialer{
// 		Proxy:             http.ProxyFromEnvironment,
// 		HandshakeTimeout:  45 * time.Second,
// 		ReadBufferSize:    1024,
// 		WriteBufferSize:   1024,
// 		EnableCompression: true,
// 	}

// 	// 尝试建立WebSocket连接
// 	conn, _, err := dialer.Dial(u.String(), nil)
// 	if err != nil {
// 		log.Printf("Failed to dial: %v", err)
// 		return false
// 	}
// 	defer conn.Close()

// 	// 如果连接成功，则认为WebSocket服务在该端口上监听
// 	return true
// }
